<?php
/**
 * ShopEx licence
 *
 * @copyright  Copyright (c) 2005-2010 ShopEx Technologies Inc. (http://www.shopex.cn)
 * @license  http://ecos.shopex.cn/ ShopEx License
 */

class aftersales_ctl_site_member extends b2c_ctl_site_member
{
    /**
     * 构造方法
     * @param object application
     */
    public function __construct(&$app)
    {
        $this->app_current = $app;
        $this->app_b2c = app::get('b2c');
        parent::__construct($this->app_b2c);
    }

    /*
     *退换货记录
     * */
    public function afterrec($type='noarchive', $nPage=1)
    {
        $this->path[] = array('title'=>app::get('b2c')->_('会员中心'),'link'=>$this->gen_url(array('app'=>'b2c', 'ctl'=>'site_member', 'act'=>'index','full'=>1)));
        $this->path[] = array('title'=>app::get('b2c')->_('退换货记录'),'link'=>'#');
        $GLOBALS['runtime']['path'] = $this->path;

        $filter = array();
        $filter["member_id"] = $this->app_b2c->member_id;
        $this->begin($this->gen_url(array('app' => 'b2c', 'ctl' => 'site_member')));
        $obj_return_policy = kernel::service("aftersales.return_policy");
        $arr_settings = array();
        if (!isset($obj_return_policy) || !is_object($obj_return_policy))
        {
            $this->end(false, app::get('aftersales')->_("售后服务应用不存在！"));
        }

        if (!$obj_return_policy->get_conf_data($arr_settings))
        {
            $this->end(false, app::get('aftersales')->_("售后服务信息没有取到！"));
        }

        if($type == 'archive'){
            $this->pagedata['type']='archive';
            $aData = $this->get_return_product_list('*', $filter, $nPage);
        }else{
            $this->pagedata['type']='noarchive';
            $aData = $obj_return_policy->get_return_product_list('*', $filter, $nPage);
        }
        foreach($aData['data'] as $key=>$val){
            $aData['data'][$key]['product_data'] = unserialize($val['product_data']);
            $aData['data'][$key]['comment'] = unserialize($val['comment']);
        }
        if (isset($aData['data']) && $aData['data'])
            $this->pagedata['return_list'] = $aData['data'];

        $imageDefault = app::get('image')->getConf('image.set');
        $this->pagedata['defaultImage'] = $imageDefault['S']['default_image'];
        $arrPager = $this->get_start($nPage, $aData['total']);
        $this->pagination($nPage, $arrPager['maxPage'], 'afterrec', array($type), 'aftersales', 'site_member');
        $this->pagedata['controller'] = 'afterlist';

        $this->output('aftersales');
    }

    /**
     * 得到满足条件的售后申请列表
     * @param string database table columns
     * @param array conditions
     * @param int page code
     * @return array 结果数组
     */
    public function get_return_product_list($clos='*', $filter = array(), $nPage=1)
    {
        $arr_return_products = array();
        $oArchiveRProduct = app::get('aftersales')->model('archive_return_product');
        $aData = $oArchiveRProduct->getList($clos,$filter,($nPage-1)*10,10,'add_time DESC');

        $count = $oArchiveRProduct->count($filter);

        return $arr_return_products = array(
            'data' => $aData,
            'total' => $count,
        );
    }

    /*
     * 申请退换货列表
     * @params int $nPage 页码
     * */
    public function afterlist($nPage=1){
    @ini_set('memory_limit','512M');
        $this->path[] = array('title'=>app::get('b2c')->_('会员中心'),'link'=>$this->gen_url(array('app'=>'b2c', 'ctl'=>'site_member', 'act'=>'index','full'=>1)));
        $this->path[] = array('title'=>app::get('b2c')->_('申请退换货'),'link'=>'#');
        $GLOBALS['runtime']['path'] = $this->path;
        $this->begin($this->gen_url(array('app' => 'aftersales', 'ctl' => 'site_member')));
        $obj_return_policy = kernel::service("aftersales.return_policy");
        $arr_settings = array();
        if (!isset($obj_return_policy) || !is_object($obj_return_policy)){
            $this->end(false, app::get('aftersales')->_("售后服务应用不存在！"));
        }

        if (!$obj_return_policy->get_conf_data($arr_settings)){
            $this->end(false, app::get('aftersales')->_("售后服务信息没有取到！"));
        }
        $order = $this->app->model('orders');
        $order_status['pay_status'] != 0;
        $order_status['ship_status'] = array(1,2,3,4);
        //$nPage查询问题参数-1，暂时改了
        $aData = $order->fetchByMember($this->app_b2c->member_id,$nPage,$order_status,15);
        $this->get_order_details($aData,'member_orders');
        $oImage = app::get('image')->model('image');
        $oGoods = app::get('b2c')->model('goods');
        $imageDefault = app::get('image')->getConf('image.set');
        foreach($aData['data'] as $k => &$v) {
            foreach($v['goods_items'] as $k2 => &$v2) {
                $spec_desc_goods = $oGoods->getList('spec_desc,image_default_id',array('goods_id'=>$v2['product']['goods_id']));
                if($v2['product']['products']['spec_desc']['spec_private_value_id']){
                    $select_spec_private_value_id = reset($v2['product']['products']['spec_desc']['spec_private_value_id']);
                    if($spec_desc_goods[0]['spec_desc']) $spec_desc_goods = reset($spec_desc_goods[0]['spec_desc']);
                }
                if($spec_desc_goods[$select_spec_private_value_id]['spec_goods_images']){
                    list($default_product_image) = explode(',', $spec_desc_goods[$select_spec_private_value_id]['spec_goods_images']);
                    $v2['product']['thumbnail_pic'] = $default_product_image;
                }elseif($spec_desc_goods[0]['image_default_id']){
                    if( !$v2['product']['thumbnail_pic'] && !$oImage->getList("image_id",array('image_id'=>$spec_desc_goods[0]['image_default_id']))){
                        $v2['product']['thumbnail_pic'] = $imageDefault['S']['default_image'];
                    }else{
                        $v2['product']['thumbnail_pic'] = $spec_desc_goods[0]['image_default_id'];
                    }
                }
            }
        }
        $this->pagedata['orders'] = $aData['data'];
        $this->pagination($nPage, $aData['pager']['total'], 'afterlist', '', 'aftersales', 'site_member');
        $this->output('aftersales');
    }

    public function gorefundlist($nPage=1){
        @ini_set('memory_limit','512M');
        $this->path[] = array('title'=>app::get('b2c')->_('会员中心'),'link'=>$this->gen_url(array('app'=>'b2c', 'ctl'=>'site_member', 'act'=>'index','full'=>1)));
        $this->path[] = array('title'=>app::get('b2c')->_('申请退款'),'link'=>'#');
        $GLOBALS['runtime']['path'] = $this->path;
        $this->begin($this->gen_url(array('app' => 'aftersales', 'ctl' => 'site_member')));
        $obj_return_policy = kernel::service("aftersales.return_policy");
        $arr_settings = array();
        if (!isset($obj_return_policy) || !is_object($obj_return_policy)){
            $this->end(false, app::get('aftersales')->_("售后服务应用不存在！"));
        }

        if (!$obj_return_policy->get_conf_data($arr_settings)){
            $this->end(false, app::get('aftersales')->_("售后服务信息没有取到！"));
        }
        $order = $this->app->model('orders');
        $order_status['ship_status'] = array(1,3,4,5);
        $aData = $order->fetchByMember($this->app_b2c->member_id,$nPage,$order_status,15);
        $oGoods = app::get('b2c')->model('goods');
        $imgIds = $oGoods->getList('goods_id,image_default_id',array('goods_id'=>$aData['goodsIds']));
        $imgIds = utils::array_bind_key($imgIds,'goods_id');
        foreach ($aData['data'] as $key => &$value) {
            foreach ($value['order_objects'] as $ke => &$val) {
                if (in_array($val['goods_id'], $aData['goodsIds'])) {
                    $val['thumbnail_pic'] = $imgIds[$val['goods_id']]['image_default_id'];
                }
                foreach ($val['order_items'] as $k => $va) {
                    $val['link_url'] = $this->gen_url(array('app'=>'b2c','ctl'=>'site_product','act'=>'index','arg0'=>$va['products']['product_id']));
                    $val['price'] = $va['price'];
                }
            }
        }
        $this->pagedata['orders'] = $aData['data'];
        $this->pagination($nPage, $aData['pager']['total'], 'gorefundlist', '', 'aftersales', 'site_member');
        $this->output('aftersales');
    }
    /**
     *售后须知页面
     */
    public function read(){
        $this->pagedata['comment'] = app::get('aftersales')->getConf('site.return_product_comment');
        $this->display('site/member/read.html','aftersales');
    }

    public function add($order_id){
        $this->begin($this->gen_url(array('app' => 'b2c', 'ctl' => 'site_member')));
        $obj_return_policy = kernel::service("aftersales.return_policy");
        $arr_settings = array();
        if (!isset($obj_return_policy) || !is_object($obj_return_policy)){
            $this->end(false, app::get('aftersales')->_("售后服务应用不存在！"),false,true);
        }
        if (!$obj_return_policy->get_conf_data($arr_settings)){
            $this->end(false, app::get('aftersales')->_("售后服务信息没有取到！"),false,true);
        }
        $objOrder = $this->app_b2c->model('orders');
        $subsdf = array('order_objects'=>array('*',array('order_items'=>array('*',array(':products'=>'*')))));
        $this->pagedata['order'] = $objOrder->dump($order_id, '*', $subsdf);
        // 校验订单的会员有效性.
        $is_verified = ($this->_check_verify_member($this->pagedata['order']['member_id'])) ? $this->_check_verify_member($this->pagedata['order']['member_id']) : false;
        // 校验订单的有效性.
        if ($_COOKIE['ST_ShopEx-Order-Buy'] != md5($this->app->getConf('certificate.token').$order_id) && !$is_verified){
            $this->end(false,  app::get('b2c')->_('订单无效！'), array('app'=>'site','ctl'=>'default','act'=>'index'),false,true);
        }
        // $this->pagedata['orderlogs'] = $objOrder->getOrderLogList($order_id);
        if(!$this->pagedata['order']){
            $this->end(false,  app::get('b2c')->_('订单无效！'), array('app'=>'site','ctl'=>'default','act'=>'index'),false,true);
        }
        $order_items = array();
        // 所有的goods type 处理的服务的初始化.
        $arr_service_goods_type_obj = array();
        $arr_service_goods_type = kernel::servicelist('order_goodstype_operation');
        foreach ($arr_service_goods_type as $obj_service_goods_type){
            $goods_types = $obj_service_goods_type->get_goods_type();
            $arr_service_goods_type_obj[$goods_types] = $obj_service_goods_type;
        }
        $objMath = kernel::single("ectools_math");
        $oImage = app::get('image')->model('image');
        $oGoods = app::get('b2c')->model('goods');
        $imageDefault = app::get('image')->getConf('image.set');
        //调用get_order_details()方法取出图片，解决图片不显示的bug，2015-10-16，by liuxin
        $image_data['data'][] = $this->pagedata['order'];
        $this->get_order_details($image_data,'member_orders');
        $mol_afterdata=app::get('aftersales')->model('return_product');
        foreach ($this->pagedata['order']['order_objects'] as $k=>&$arrOdr_object){
            $index = 0;
            $index_adj = 0;
            $index_gift = 0;
            $tmp_array = array();
            if($arrOdr_object['obj_type'] == 'timedbuy'){
                $arrOdr_object['obj_type'] = 'goods';
            }
            if ($arrOdr_object['obj_type'] == 'goods'){
                foreach($arrOdr_object['order_items'] as $key => &$item){
                    //查询已退数量
                    $yt_num = $mol_afterdata->getNum($order_id,$item['bn']);
                    if (!$yt_num) {
                        $yt_num=0;
                    }
                    $item['yt_num'] = $yt_num;
                    if ($item['item_type'] == 'product')
                        $item['item_type'] = 'goods';
                    if ($tmp_array = $arr_service_goods_type_obj[$item['item_type']]->get_aftersales_order_info($item)){
                        $tmp_array = (array)$tmp_array;
                        if (!$tmp_array) continue;
                        $product_id = $tmp_array['products']['product_id'];
                        if (!$order_items[$product_id]){
                            $tmp_array['arrNum'] = $this->intArray($tmp_array['quantity']);
                            $order_items[$product_id] = $tmp_array;
                        }else{
                            $order_items[$product_id]['sendnum'] = floatval($objMath->number_plus(array($order_items[$product_id]['sendnum'],$tmp_array['sendnum'])));
                            $order_items[$product_id]['quantity'] = floatval($objMath->number_plus(array($order_items[$product_id]['quantity'],$tmp_array['quantity'])));
                            $order_items[$product_id]['arrNum'] = $this->intArray($order_items[$product_id]['quantity']);
                        }
                        // 货品图片
                        $spec_desc_goods = $oGoods->getList('spec_desc,image_default_id',array('goods_id'=>$item['goods_id']));
                        if($item['products']['spec_desc']['spec_private_value_id']){
                            $select_spec_private_value_id = reset($item['products']['spec_desc']['spec_private_value_id']);
                            $spec_desc_goods = reset($spec_desc_goods[0]['spec_desc']);
                        }
                        if($spec_desc_goods[$select_spec_private_value_id]['spec_goods_images']){
                            list($default_product_image) = explode(',', $spec_desc_goods[$select_spec_private_value_id]['spec_goods_images']);
                            $order_items[$product_id]['thumbnail_pic'] = $default_product_image;
                        }elseif($spec_desc_goods[0]['image_default_id']){
                            if( !$order_items[$product_id]['thumbnail_pic'] && !$oImage->getList("image_id",array('image_id'=>$spec_desc_goods[0]['image_default_id']))){
                                $order_items[$product_id]['thumbnail_pic'] = $imageDefault['S']['default_image'];
                            }else{
                                $order_items[$product_id]['thumbnail_pic'] = $spec_desc_goods[0]['image_default_id'];
                            }
                        }else{//增加else，解决图片不显示的bug，2015-10-16，by liuxin
                            $order_items[$product_id]['thumbnail_pic'] = $image_data['data']['0']['goods_items'][ $k]['product']['thumbnail_pic'];
                            $order_items[$product_id]['link_url'] = $image_data['data']['0']['goods_items'][ $k]['product']['link_url'];
                        }
                        //$order_items[$item['products']['product_id']] = $tmp_array;
                    }
                }
            }else{
                if ($tmp_array = $arr_service_goods_type_obj[$arrOdr_object['obj_type']]->get_aftersales_order_info($arrOdr_object)){
                    $tmp_array = (array)$tmp_array;
                    if (!$tmp_array) continue;
                    foreach ($tmp_array as $tmp){
                        if (!$order_items[$tmp['product_id']]){
                            $tmp['arrNum'] = $this->intArray($tmp['quantity']);
                            $order_items[$tmp['product_id']] = $tmp;
                        }else{
                            $order_items[$tmp['product_id']]['sendnum'] = floatval($objMath->number_plus(array($order_items[$tmp['product_id']]['sendnum'],$tmp['sendnum'])));
                            $order_items[$tmp['product_id']]['nums'] = floatval($objMath->number_plus(array($order_items[$tmp['product_id']]['nums'],$tmp['nums'])));
                            $order_items[$tmp['product_id']]['quantity'] = floatval($objMath->number_plus(array($order_items[$tmp['product_id']]['quantity'],$tmp['quantity'])));
                            $order_items[$tmp['product_id']]['arrNum'] = $this->intArray($order_items[$tmp['product_id']]['quantity']);
                        }
                    }
                }
                //$order_items = array_merge($order_items, $tmp_array);
            }
        }
        $this->pagedata['order_id'] = $order_id;
        $this->pagedata['order']['items'] = $order_items;
        $this->pagedata['controller'] = 'afterlist';
        $this->output('aftersales');
    }

    private function intArray($int=1){
        for($i=1;$i<=$int;$i++){
            $return[$i] = $i;
        }
        return $return;
    }

    /**
     * 截取文件名不包含扩展名
     * @param 文件全名，包括扩展名
     * @return string 文件不包含扩展名的名字
     */
    private function fileext($filename)
    {
        return substr(strrchr($filename, '.'), 1);
    }

    /*
     *无刷新上传图片，返回信息
     * */
    public function ajax_callback($status='error',$msg,$url=''){
        header('Content-Type:text/html; charset=utf-8');
        echo '<script>parent.ajax_callback1("'.$status.'","'.$msg.'","'.$url.'")</script>';exit;
    }

    public function return_save(){
        $obj_return_policy = kernel::service("aftersales.return_policy");
        $arr_settings = array();
        if (!isset($obj_return_policy) || !is_object($obj_return_policy)){
            $this->ajax_callback('error',app::get('aftersales')->_("售后服务应用不存在！"));
        }
        if (!$obj_return_policy->get_conf_data($arr_settings)){
            $this->ajax_callback('error',app::get('aftersales')->_("售后服务信息没有取到！"));
        }
        if (!$_POST['product_bn']){
            $this->ajax_callback('error',app::get('aftersales')->_("您没有选择商品，请先选择商品！"));
        }
        if (!$_POST['title']){
            $this->ajax_callback('error',app::get('aftersales')->_("请填写退货理由"));
        }
        $upload_file = "";
        if ( $_FILES['file']['size'] > 314572800 ){
            $this->ajax_callback('error',app::get('aftersales')->_("上传文件不能超过300M！"));
        }
        if ( $_FILES['file']['name'] != "" ){
            $type=array("png","jpg","gif","jpeg","rar","zip");
            if(!in_array(strtolower($this->fileext($_FILES['file']['name'])), $type)){
                $text = implode(",", $type);
                $this->end(false, app::get('aftersales')->_("您只能上传以下类型文件: ") . $text . "<br>", $com_url,false,$_POST['response_json']);
                $this->ajax_callback('error',app::get('aftersales')->_("您只能上传以下类型文件: ") . $text . "<br>");
            }
            $mdl_img = app::get('image')->model('image');
            $image_name = $_FILES['file']['name'];
            $image_id = $mdl_img->store($_FILES['file']['tmp_name'],null,null,$image_name);
            $mdl_img->rebuild($image_id,array('L','M','S'));
            if (isset($_REQUEST['type'])){
                $type = $_REQUEST['type'];
            }else{
                $type = 's';
            }
            $image_src = base_storager::image_path($image_id, $type);
        }
        if(!$_POST['agree']){
            $this->ajax_callback('error',app::get('aftersales')->_("请先查看售后服务须知并且同意"));
        }
        $obj_filter = kernel::single('b2c_site_filter');
        $_POST = $obj_filter->check_input($_POST);
        $product_data = array();
        //退换货时判断数量是否大于购买数量-已退换数量，2015-10-12，by liu
        $mol_afterdata=app::get('aftersales')->model('return_product');
        foreach ((array)$_POST['product_bn'] as $key => $val){
            if (intval($_POST['product_nums'][$key]==0) || !$_POST['product_nums'][$key] ) {
                $this->ajax_callback('error','退换货数量不能为0');
                exit;
            }
            $item = array();
            $item['bn'] = $val;
            $item['name'] = $_POST['product_name'][$key];
            $item['num'] = floatval($_POST['product_nums'][$key]);
            $item['price'] = floatval($_POST['product_price'][$key]);
            $yt_num = $mol_afterdata->getNum($_POST['order_id'],$val);
            if (!$yt_num) {
                $yt_num=0;
            }
            if($_POST['product_nums'][$key]> ($_POST['product_num'][$key]-$yt_num)){
                $this->ajax_callback('error','退换货数量超出已购买数量！');
                exit;
            }
            $product_data[] = $item;
        }
        $aData['order_id'] = $_POST['order_id'];
        $aData['title'] = $_POST['title'];
        $aData['type'] = $_POST['type']==2 ? 2 : 1;
        $aData['add_time'] = time();
        $aData['image_file'] = $image_id;
        $aData['member_id'] = $this->app_b2c->member_id;
        $aData['product_data'] = serialize($product_data);
        $aData['content'] = $_POST['content'];
        $aData['status'] = 2;
        $msg = "";
        $obj_aftersales = kernel::service("api.aftersales.request");
        if ($obj_aftersales && $obj_aftersales->generate($aData, $msg)){
            $obj_rpc_request_service = kernel::service('b2c.rpc.send.request');
            if ($obj_rpc_request_service && method_exists($obj_rpc_request_service, 'rpc_caller_request')){
                if ($obj_rpc_request_service instanceof b2c_api_rpc_request_interface)
                    $obj_rpc_request_service->rpc_caller_request($aData,'aftersales');
            }else{
                $obj_aftersales->rpc_caller_request($aData);
            }
            $this->ajax_callback('success',app::get('aftersales')->_("提交成功"),$this->gen_url(array('app' => 'aftersales', 'ctl' => 'site_member', 'act' => 'afterrec')));
        }else{
            $this->ajax_callback('error',$msg);
        }
    }

    public function return_details($return_id)
    {
        $this->begin($this->gen_url(array('app' => 'b2c', 'ctl' => 'site_member')));
        $obj_return_policy = kernel::service("aftersales.return_policy");
        $arr_settings = array();

        if (!isset($obj_return_policy) || !is_object($obj_return_policy))
        {
            $this->end(false, app::get('aftersales')->_("售后服务应用不存在！"));
        }

        if (!$obj_return_policy->get_conf_data($arr_settings))
        {
            $this->end(false, app::get('aftersales')->_("售后服务信息没有取到！"));
        }

        $this->pagedata['return_item'] =  $obj_return_policy->get_return_product_by_return_id($return_id);
        $this->pagedata['return_id'] = $return_id;
        if( !($this->pagedata['return_item']) )
        {
           $this->begin($this->gen_url(array('app' => 'aftersales', 'ctl' => 'site_member', 'act' => 'return_list')));
           $this->end(false, $this->app->_("售后服务申请单不存在！"));
        }

        $this->output('aftersales');
    }

    /**
     * 下载售后附件
     * @param string return id
     * @return null
     */
    public function file_download($return_id)
    {
        $obj_return_policy = kernel::service("aftersales.return_policy");
        $obj_return_policy->file_download($return_id);
    }

    public function return_order_items($order_id){
        $objOrder = $this->app_b2c->model('orders');
        $subsdf = array('order_objects'=>array('*',array('order_items'=>array('*',array(':products'=>'*')))));
        $orderinfo = $objOrder->dump($order_id, '*', $subsdf);

        $order_items = array();
        // 所有的goods type 处理的服务的初始化.
        $arr_service_goods_type_obj = array();
        $arr_service_goods_type = kernel::servicelist('order_goodstype_operation');
        foreach ($arr_service_goods_type as $obj_service_goods_type)
        {
            $goods_types = $obj_service_goods_type->get_goods_type();
            $arr_service_goods_type_obj[$goods_types] = $obj_service_goods_type;
        }

        $objMath = kernel::single("ectools_math");
        foreach ($orderinfo['order_objects'] as $k=>$arrOdr_object)
        {
            $tmp_array = array();
            if($arrOdr_object['obj_type'] == 'timedbuy'){
                $arrOdr_object['obj_type'] = 'goods';
            }
            if ($arrOdr_object['obj_type'] == 'goods'){
                foreach($arrOdr_object['order_items'] as $key => $item){
                    if ($item['item_type'] == 'product'){
                        $item['item_type'] = 'goods';
                    }

                    if ($tmp_array = $arr_service_goods_type_obj[$item['item_type']]->get_aftersales_order_info($item)){
                        $tmp_array = (array)$tmp_array;
                        if (!$tmp_array) continue;

                        $product_id = $tmp_array['products']['product_id'];
                        if (!$order_items[$product_id]){
                            $order_items[$product_id] = $tmp_array;
                        }else{
                            $order_items[$product_id]['sendnum'] = floatval($objMath->number_plus(array($order_items[$product_id]['sendnum'],$tmp_array['sendnum'])));
                            $order_items[$product_id]['quantity'] = floatval($objMath->number_plus(array($order_items[$product_id]['quantity'],$tmp_array['quantity'])));
                        }
                    }
                    unset($order_items[$product_id]['products']);
                }
            }else{
                if ($tmp_array = $arr_service_goods_type_obj[$arrOdr_object['obj_type']]->get_aftersales_order_info($arrOdr_object)){
                    $tmp_array = (array)$tmp_array;
                    if (!$tmp_array) continue;
                    foreach ($tmp_array as $tmp){
                        if (!$order_items[$tmp['product_id']]){
                            $order_items[$tmp['product_id']] = $tmp;
                        }else{
                            $order_items[$tmp['product_id']]['sendnum'] = floatval($objMath->number_plus(array($order_items[$tmp['product_id']]['sendnum'],$tmp['sendnum'])));
                            $order_items[$tmp['product_id']]['nums'] = floatval($objMath->number_plus(array($order_items[$tmp['product_id']]['nums'],$tmp['nums'])));
                            $order_items[$tmp['product_id']]['quantity'] = floatval($objMath->number_plus(array($order_items[$tmp['product_id']]['quantity'],$tmp['quantity'])));
                        }
                        unset($order_items[$tmp['product_id']]['products']);
                    }
                }
            }
        }

        return $order_items;
    }
    public function go_refund($order_id){
        $this->begin($this->gen_url(array('app' => 'b2c', 'ctl' => 'site_member')));
        $obj_return_policy = kernel::service("aftersales.return_policy");
        $arr_settings = array();
        if (!isset($obj_return_policy) || !is_object($obj_return_policy)){
            $this->end(false, app::get('aftersales')->_("售后服务应用不存在！"),false,true);
        }
        if (!$obj_return_policy->get_conf_data($arr_settings)){
            $this->end(false, app::get('aftersales')->_("售后服务信息没有取到！"),false,true);
        }
        $objOrder = $this->app_b2c->model('orders');
        $subsdf = array('order_objects'=>array('*',array('order_items'=>array('*',array(':products'=>'*')))));
        $this->pagedata['order'] = $orderinfo = $objOrder->dump($order_id, '*', $subsdf);

        if (!in_array($orderinfo['ship_status'], array(3,4,5))) {
            $this->end(false, app::get('aftersales')->_("该订单没有取消发货或没有退换货成功,不能退款。"),false,true);
        }
        // 校验订单的会员有效性.
        $is_verified = ($this->_check_verify_member($this->pagedata['order']['member_id'])) ? $this->_check_verify_member($this->pagedata['order']['member_id']) : false;
        // 校验订单的有效性.
        if ($_COOKIE['ST_ShopEx-Order-Buy'] != md5($this->app->getConf('certificate.token').$order_id) && !$is_verified){
            $this->end(false,  app::get('b2c')->_('订单无效！'), false,true);
        }
        // $this->pagedata['orderlogs'] = $objOrder->getOrderLogList($order_id);
        if(!$this->pagedata['order']){
            $this->end(false,  app::get('b2c')->_('订单无效！'), false,true);
        }
        $this->pagedata['order_id'] = $order_id;
        if ($apply_id) {
            $_SESSION['apply_id'] = $apply_id;
        }else{
            $_SESSION['apply_id'] = $this->gen_applyid();
        }
        $this->pagedata['apply_id'] = $_SESSION['apply_id'];
        $this->output('aftersales');
    }
    //开票信息
    public function go_billing(){
        // dump($_POST);dump($_GET);
        //获取对应客户member_id
        $member_id=$this->app->member_id;
        $this->pagedata['member_id']=$member_id;
        //添加开票额度在用户表
//        $dbName='jxc_oubao';
//        $sql="select billing_money from {$dbName}.jichu_client where member_id in({$member_id})";
//        $billMoney=kernel::database()->select($sql);
//        $billing_advance=$billMoney[0]['billing_money'];
//        $arr_list=array();
//        $arr_list['member_id']=$member_id;
//        $arr_list['billing_advance']=$billing_advance;
//        $advance_list=app::get('b2c')->model('members');
//        $rowstr=$advance_list->save($arr_list);
        $this->output('aftersales');
    }
     public function go_billings(){

        //获取对应客户member_id
        $member_id=$this->app->member_id;
        $this->pagedata['member_id']=$member_id;

        $this->output('aftersales');
    }
    public function array_col_values(& $arr,$col){
        $ret=array();
        foreach($arr as $kk){
            if(isset($kk[$col])){
                $ret[]=$kk[$col];
            }
        }
        return $ret;
    }
    //去申请
    public function to_billing(){
        $data=$_POST;
        //专用发票 --单位
        if(isset($data['company_taxpayer']) && !empty($data['company_taxpayer'])){
            $biling_info=$this->get_addbilling($data['member_id']);
            if(empty($biling_info)){
                $this->ajax_callback('error',app::get('aftersales')->_('请在增票资质中添加纳税人信息'));
            }
        }
        $mobile=preg_match("/^1[35678]{1}[0-9]{9}|0\d{2,3}-\d{5,9}|0\d{2,3}-\d{5,9}$/", $data['company_mobile']);
        $email=preg_match("/^[a-zA-Z0-9_-]+@[a-zA-Z0-9_-]+(\.[a-zA-Z0-9_-]+)+$/", $data['company_email']);
        if($_POST['zhuanyong']){
            if(!$mobile){
                $this->ajax_callback('error',app::get('aftersales')->_("手机号格式有误"));
            }
            if(!$email){
                $this->ajax_callback('error',app::get('aftersales')->_("邮箱格式有误"));
            }
            $billing_type=$_POST['zhuanyong'];
        }elseif($_POST['putong']){
            $billing_type=$_POST['putong'];
        }
        if($_POST['positive']){
            $rise_billing=$_POST['positive'];
        }elseif($_POST['danwei']){
            $rise_billing=$_POST['danwei'];
        }
        $member_id=$this->app->member_id;
//        foreach($items as $kk=>$vv){
//            if($vv['order_id']==$data['order_id']){
//                $sql2="select total_amount from sdb_b2c_orders where order_id='{$vv['order_id']}'";
//                $total_amount=kernel::database()->select($sql2);
//                // dump($total_amount);die;
//                $arrs[]=$vv;
//            }
//        }
//        $bn=$this->array_col_values($arrs,'bn');
//        $num=$this->array_col_values($arrs,'nums');
//        $amount=$this->array_col_values($arrs,'amount');
//        $bn=implode(',',$bn);
//        $billing_money=array_sum($amount);
//        $nums=array_sum($num);
        // $total_adv=app::get('b2c')->model('member_advance')->getList('*',array('member_id'=>$member_id));

//        $dbName='jxc_oubao';
//        $sql="select billing_money from {$dbName}.jichu_client where member_id in({$member_id})";
//        $billMoney=kernel::database()->select($sql);
//        $billing_advance=$billMoney[0]['billing_money'];
//        $moneyId=$billing_advance;
        $billing_advance=$this->get_member_billing($member_id);
        // $billingmoney=$this->get_member_billing($this->app->member_id);
        if($data['billing_money']>$billing_advance){
            $this->ajax_callback('error',app::get('aftersales')->_("开票金额不能大于剩余开票额度！"));
        }
        // dump($moneyId);
        // dump($billing_advance);dump($data['billing_money']);die;
        $aData=array(
            'member_id'=>$member_id,
            'billing_id'=>mktime(),
            'status'=>'1',
            'billing_money'=>$data['billing_money'],
            'billing_type'=>$billing_type.'',
            'rise_billing'=>$rise_billing,
            'company_taxpayer'=>$data['company_taxpayer'].'',
            'company_name'=>$data['company_name'].'',
            'content'=>$data['content'].'',
            'company_mobile'=>$data['company_mobile'].'',
            'company_email'=>$data['company_email'],
            'company_memo'=>$data['company_memo'],
            'last_modify'=>time(),
        );
        $objRow=kernel::single('aftersales_data_billing');
        $objRow->saveBilling($aData);
        $this->pagedata['billing_advance']=$billing_advance;
        $this->pagedata['member_id']=$member_id;
        $this->ajax_callback('success',app::get('aftersales')->_("申请成功，请等待审核"),$this->gen_url(array('app' => 'aftersales', 'ctl' => 'site_member', 'act' => 'go_billing')));
    }

    /**
     * @Desc:调用进销存api,获得该会员的开票额度
     * @author:guomin
     * @date:2018-03-12 14:51
     * @param string $member_id
     * @return string
     */
    private function get_member_billing($member_id){

        //注意以下格式不能变化,2015-9-10 by jeff
        $post = array(
            'method'=>'jichu.getMemberBilling',
            'params'=>array(
                'member_id'=>$member_id,
            )
        );
        $erp_caller_obj = kernel::service('apioubao.rpc_erp_request');
        $result = $erp_caller_obj->call_api_oubao($post);
        $result=json_decode($result,true);
        return $result['data']['billing_money'];
    }

    /**
     * @desc获取开票记录明细审核状态
     * @author guomin
     * @date 2018/4/28  9:52
     * @param string $billing_id
     * @return string
     */
    public function get_apply_billing_status($billing_id){
        //注意以下格式不能变化,2015-9-10 by jeff
        $post = array(
            'method'=>'jichu.getApplyBillingStatus',
            'params'=>array(
                'billing_id'=>$billing_id,
            )
        );
        $erp_caller_obj = kernel::service('apioubao.rpc_erp_request');
        $result = $erp_caller_obj->call_api_oubao($post);
        $result=json_decode($result,true);
        //consoleLog($result);
        return $result['data']['shenhe'];
    }
    public function go_addbilling(){
        //获取对应客户member_id
        $member_id=$this->app->member_id;
        $this->pagedata['member_id']=$member_id;
        $this->output('aftersales');
    }
    public function to_addbilling(){
        $data=$_POST;
        $back_url = app::get('site')->router()->gen_url(array('app'=>'aftersales','ctl'=>'site_member','act'=>'go_addbilling'));

        $match="/^1[35678]{1}[0-9]{9}|\d{3,5}-\d{7,8}$/";
        $preg=preg_match($match, $data['company_mobile']);
        if(!$preg){
            $this->ajax_callback('error',app::get('aftersales')->_("电话格式有误"));
        }
        // $bMatch="/^[0-9]{17}|[0-9]{18}|[0-9]{19}|[0-9]{20}|[0-9]{21}$/";
        // 银行号不作判断
        // $bMatch="/^[0-9]{15,21}$/";
        // $bank=preg_match($bMatch, $data['bank_account']);
        // if(!$bank){
        //      $this->ajax_callback('error',app::get('aftersales')->_("银行账户至少18位数"));
        // }
        // die;
        $arr=app::get('aftersales')->model('apply_addbilling');
        $aData=array(
            'member_id'=>$this->app->member_id,
            'company'=>$data['company'],
            'company_taxpayer'=>$data['company_taxpayer'],
            'company_addr'=>$data['company_addr'],
            'company_mobile'=>$data['company_mobile'],
            'open_bank'=>$data['open_bank'],
            'bank_account'=>$data['bank_account'],
            'last_modify'=>time(),
        );
        // dump($aData);die;
        $rows=$arr->save($aData);
        $this->ajax_callback('success',app::get('aftersales')->_("添加成功"),$this->gen_url(array('app' => 'aftersales', 'ctl' => 'site_member', 'act' => 'go_addbilling')));
        $this->pagedata['member_id']=$member_id;
    }
    public function instructions_billing(){
        //获取对应客户member_id
        $member_id=$this->app->member_id;
        $this->pagedata['member_id']=$member_id;
        $this->output('aftersales');
    }

    /**
     * @Desc:获取增票资质
     * @author:guomin
     * @date:2018-03-06 15:08
     * @param $memberId
     * @return array
     */
    private function get_addbilling($memberId){
        $member_id=app::get('aftersales')->model('apply_addbilling')->getList('*',array('member_id'=>$memberId));
        return $member_id;
    }

    public function select_billing(){
        // dump($_GET);
        // dump($_POST);die;
        //添加增票资质
        $member_id=$this->get_addbilling($_POST['member_id']);
        if(!$member_id){
            echo "纳税人的ID号不存在!";
            exit;
        }
       // $order=app::get('b2c')->model('orders');
        //$rows=$order->fetchByMember($this->app->member_id,1);


        $this->pagedata['rolls'] = $member_id;
        $select_billing=true;
        $this->pagedata['select_billing']=$select_billing;
        echo $this->fetch('site/product/select_billing.html');
        // $this->output('aftersales');
    }
    public function select_order(){

        $order=app::get('b2c')->model('orders');
        $rows=$order->getList('order_id,total_amount',array('member_id'=>$this->app->member_id));
        $this->pagedata['order_id']=$rows;
        $this->pagedata['member_id']=$this->app->member_id;
        // dump($rows);die;
        echo $this->fetch('site/product/select_order.html');
    }

    public function refundrecord($nPage=1){
        $this->path[] = array('title'=>app::get('b2c')->_('会员中心'),'link'=>$this->gen_url(array('app'=>'b2c', 'ctl'=>'site_member', 'act'=>'index','full'=>1)));
        $this->path[] = array('title'=>app::get('b2c')->_('退款记录'),'link'=>'#');
        $GLOBALS['runtime']['path'] = $this->path;
        $filter = array();
        $filter["member_id"] = $this->app_b2c->member_id;
        $this->begin($this->gen_url(array('app' => 'b2c', 'ctl' => 'site_member')));
        $obj_return_policy = kernel::service("aftersales.return_policy");
        $arr_settings = array();
        if (!isset($obj_return_policy) || !is_object($obj_return_policy))
        {
            $this->end(false, app::get('aftersales')->_("售后服务应用不存在！"));
        }

        if (!$obj_return_policy->get_conf_data($arr_settings))
        {
            $this->end(false, app::get('aftersales')->_("售后服务信息没有取到！"));
        }
        $aData = $this->get_refund_apply_list('*', $filter, $nPage);
        if (isset($aData['data']) && $aData['data'])
            $this->pagedata['return_list'] = $aData['data'];
        $arrPager = $this->get_start($nPage, $aData['total']);
        $this->pagination($nPage, $arrPager['maxPage'], 'refundrecord', array(), 'aftersales', 'site_member');
        $this->output('aftersales');
    }

    //开票记录
    public function apply_billing($nPage=1){
        $this->path[] = array('title'=>app::get('b2c')->_('会员中心'),'link'=>$this->gen_url(array('app'=>'b2c', 'ctl'=>'site_member', 'act'=>'index','full'=>1)));
        $this->path[] = array('title'=>app::get('b2c')->_('开票记录'),'link'=>'#');
        $GLOBALS['runtime']['path'] = $this->path;
        $filter["member_id"] = $this->app_b2c->member_id;
        $this->begin($this->gen_url(array('app' => 'b2c', 'ctl' => 'site_member')));
        $obj_return_policy = kernel::service("aftersales.return_policy");
        $arr_settings = array();
        if (!isset($obj_return_policy) || !is_object($obj_return_policy))
        {
            $this->end(false, app::get('aftersales')->_("开票申请应用不存在！"));
        }
        if (!$obj_return_policy->get_conf_data($arr_settings))
        {
            $this->end(false, app::get('aftersales')->_("开票申请信息没有取到！"));
        }
        $aData = $this->get_billing_apply_list('*', $filter, $nPage);
        if (isset($aData['data']) && $aData['data']){
            foreach ($aData['data'] as &$value){
                $status=$this->get_apply_billing_status($value['billing_id']);
                if($status=='yes'){
                    $value['status']=2;
                }elseif ($status=='no'){
                    $value['status']=3;
                }else{
                    $value['status']=1;
                }
            }
            $this->pagedata['return_list'] = $aData['data'];
        }
        $arrPager = $this->get_start($nPage, $aData['total']);
        //怎么能这样写?? 2018-7-25
//        $dbName='jxc_oubao';
//        $sql="select billing_money from {$dbName}.jichu_client where member_id in({$filter["member_id"]})";
//        $billMoney=kernel::database()->select($sql);
//        $arr_money=array();
//        foreach($billMoney as $k=>$v){
//
//            $arr_money=$v;
//        }
        //添加开票额度在用户表    写这一步的意义何在？？
//        $arr_list=array();
//        $arr_list['member_id']=$filter['member_id'];
//        $arr_list['billing_advance']=$arr_money['billing_money'];
//        $advance_list=app::get('b2c')->model('members');
//        $rowstr=$advance_list->save($arr_list);
        $this->pagedata['billing_advance']=$this->get_member_billing($filter["member_id"]);
        $this->pagination($nPage, $arrPager['maxPage'], 'apply_billing', array(), 'aftersales', 'site_member');
        $this->output('aftersales');
    }
    public function apply_addbilling($nPage=1){
        $this->path[]=array('title'=>app::get('b2c')->_('会员中心'),'link'=>$this->gen_url(array('app'=>'b2c','ctl'=>'site_member','act'=>'index','full'=>1)));
        $this->path[]=array('title'=>app::get('b2c')->_('增值记录'),'link'=>'#');
          $GLOBALS['runtime']['path']=$this->path;
        $filter['member_id']=$this->app->member_id;
        // dump($filter);die;
        $aData=$this->get_addbilling_apply_list('*',$filter,$nPage);
        if(isset($aData['data'])&&$aData['data'])
            $this->pagedata['addbilling_list']=$aData['data'];
        $arrPager=$this->get_start($nPage,$aData['total']);
        $this->pagination($nPage,$arrPager['maxPage'],'apply_addbilling',array(),'aftersales','site_member');

        $this->output('aftersales');
    }
     //删除增值内容
    public  function del_apply($addrId=null){
        $member_id=$this->app->member_id;
        if($addrId && $member_id){
            $member_addr = app::get('aftersales')->model('apply_addbilling');
             $filter = array('id' => $addrId,'member_id'=>$member_id);
             if($filter){
                $delete=$member_addr->delete($filter);
                $meesage = app::get('aftersales')->_("删除成功");
                return true;
             }
             else{
                 $meesage = app::get('aftersales')->_("删除失败");
                   return true;
             }

        }else{
            $meesage = app::get('aftersales')->_("删除失败");
             return false;
        }
    }
    //修改增值内容
    public function edit_addbilling($edit=null){
        $edit_id=app::get('aftersales')->model('apply_addbilling');
        $rows=$edit_id->getList('*',array('id'=>$edit));
        // dump($rows);die;
        $this->pagedata['edit_list']=$rows;
        $this->pagedata['update_id']=$edit;
        $this->output('aftersales');
    }
    //修改信息
    public function update_addbilling(){
        $data=$_POST;
        $arr=app::get('aftersales')->model('apply_addbilling');
        $aData=array(
            'id'=>$data['update_id'],
            'member_id'=>$this->app->member_id,
            'company'=>$data['company'],
            'company_taxpayer'=>$data['company_taxpayer'],
            'company_addr'=>$data['company_addr'],
            'company_mobile'=>$data['company_mobile'],
            'open_bank'=>$data['open_bank'],
            'bank_account'=>$data['bank_account'],
            'last_modify'=>time(),
        );
        // dump($aData);die;
        if($data['update_id']){
            $arr->update($aData,array('id'=>$data['update_id']));
            // dump($data);die;
            $this->ajax_callback('success',app::get('aftersales')->_("修改成功"),$this->gen_url(array('app' => 'aftersales', 'ctl' => 'site_member', 'act' => 'apply_addbilling')));

        }


    }

    public function to_refund(){
        $data = $_POST;
        $order = $this->app->model('orders');
        //判断退款金额
        $orderInfo = $order->getRow('*',array('order_id'=>$data['order_id']));
        if ($data['apply_money']>$orderInfo['final_amount']) {
            $this->ajax_callback('error',app::get('aftersales')->_("申请金额不能大于付款金额！"),null);
        }
        if ($data['apply_id'] ==$_SESSION['apply_id']) {
            unset($_SESSION['apply_id']);
            $member_id = $this->app_b2c->member_id;
            $data['member_id'] = $member_id;
            $data['add_time'] = time();
            $data['status'] = 1;
            $objRefund = kernel::single('aftersales_data_refund');
            $ret = $objRefund->saveRefund($data);
            $this->ajax_callback('success',app::get('aftersales')->_("申请成功，请等待审核"),$this->gen_url(array('app' => 'aftersales', 'ctl' => 'site_member', 'act' => 'gorefundlist')));
        }else{
            $this->ajax_callback('error',app::get('aftersales')->_("您已申请，请勿重复提交"),$this->gen_url(array('app' => 'aftersales', 'ctl' => 'site_member', 'act' => 'gorefundlist')));
        }
    }

    public function gen_applyid() {
        $i = rand(0,9999);
        $return_id = date('YmdH').str_pad($i,4,'0',STR_PAD_LEFT);
        return $return_id;
    }
    public function get_refund_apply_list($clos='*', $filter=array(), $nPage=1){
        $ret = array();
        $mdlApply = app::get('aftersales')->model('apply_refund');
        $aData = $mdlApply->getList($clos,$filter,($nPage-1)*10,10,'add_time DESC');
        $count = $mdlApply->count($filter);
        return $ret = array(
            'data' => $aData,
            'total' => $count,
        );
    }
    //获取开票记录数据组
    public function get_billing_apply_list($clos="*",$filter=array(),$nPage=1){
        $ret=array();
        $mdApply=app::get('aftersales')->model('apply_billing');
        $aData=$mdApply->getList($clos,$filter,($nPage-1)*10,10,'last_modify DESC');
        $count=$mdApply->count($filter);
        return $ret=array(
            'data'=>$aData,
            'total'=>$count,
        );
    }
    //获取增值记录
    public function get_addbilling_apply_list($clos="*",$filter=array(),$nPage=1){
        $arr=array();
        $addApp=app::get('aftersales')->model('apply_addbilling');
        $aData=$addApp->getList($clos,$filter,($nPage-1)*10,10,'id DESC');
        $count=$addApp->count($filter);
        return $arr=array(
            'data'=>$aData,
            'total'=>$count,
        );
    }
    //重新申请退款
    public function again_refund($order_id,$apply_id){
        $objRefund = app::get('aftersales')->model('apply_refund');
        $refundInfo = $objRefund->getRow('*',array('apply_id'=>$apply_id));
        $objOrder = $this->app_b2c->model('orders');
        $this->pagedata['order'] = $orderinfo = $objOrder->getRow('*',array('order_id'=>$order_id));
        $this->pagedata['order_id'] = $order_id;
        $this->pagedata['refundInfo'] = $refundInfo;
        $_SESSION['apply_id'] = $apply_id;
        $this->output('aftersales');
    }
    public function to_again_refund(){
        $data = $_POST;
        $order = $this->app->model('orders');
        //判断退款金额
        $orderInfo = $order->getRow('*',array('order_id'=>$data['order_id']));
        if ($data['apply_money']>$orderInfo['final_amount']) {
            $this->ajax_callback('error',app::get('aftersales')->_("申请金额不能大于付款金额！"),$this->gen_url(array('app' => 'aftersales', 'ctl' => 'site_member', 'act' => 'gorefundlist')));
        }
        if ($data['apply_id'] ==$_SESSION['apply_id']) {
            unset($_SESSION['apply_id']);
            $member_id = $this->app_b2c->member_id;
            $data['member_id'] = $member_id;
            $data['add_time'] = time();
            $data['status'] = 1;
            $objRefund = kernel::single('aftersales_data_refund');
            $ret = $objRefund->saveRefund($data);
            $this->ajax_callback('success',app::get('aftersales')->_("申请成功，请等待审核"),$this->gen_url(array('app' => 'aftersales', 'ctl' => 'site_member', 'act' => 'gorefundlist')));
        }else{
            $this->ajax_callback('error',app::get('aftersales')->_("您已申请，请勿重复提交"),$this->gen_url(array('app' => 'aftersales', 'ctl' => 'site_member', 'act' => 'gorefundlist')));
        }
    }

    /*
        //特殊情况处理（针对预存款）：jxc审核退款审核成功了，但ec没有收到预存款，发现ec后台订单售后状态是已经拒绝的。
        临时处理：
        手动修改：
        1.根据订单号修改sdb_b2c_orders的字段redelivery_status=2；
        2.根据申请的apply_id 修改sdb_aftersales_apply_refund的字段status=1；审核中
        3.根据订单号 修改sdb_aftersales_return_product的字段status=4;
        4.在执行此方法：/aftersales-changeRefundStatus-xxx.html。(xxx表示apply_id)。
    */
    public function changeRefundStatus($apply_id){
        $mdlApplyRefund = app::get('aftersales')->model('apply_refund');
        //判断申请退款状态
        /*
        array(
        '1' => app::get('aftersales')->_('审核中'),
        '2' => app::get('aftersales')->_('完成'),
        '3' => app::get('aftersales')->_('拒绝'),
        ),
        */
        //如果已经退款完成 =2 则不执行，避免重复
        $flag = $mdlApplyRefund->count(array('apply_id'=>$apply_id,'status'=>2));
        if ($flag) {
            echo '不执行，避免重复';
            return false;
        }
        $mdlApplyRefund->update(array('status'=>$data['status'],'admin_content'=>$data['memo']),array('apply_id'=>$data['apply_id']));
        $data = array(
            'status'=>2,
            'apply_id'=>$apply_id,
            'refund_type'=>'deposit',
            'memo'=>'-',
        );
        kernel::single('aftersales_data_refund')->changeRefund($data);
        echo '执行成功';
    }
}
